package com.dbs.task.async;

import java.util.Random;
import java.util.concurrent.Future;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

/**
 * 同步调用 用于比较异步
 * 
 * @author dongbisheng
 * @date Apr 14, 2017 11:01:36 AM
 */
@Component
public class NormalTask {
	public static Random random = new Random();

	public Future<String> doTaskOne() throws Exception {
		System.out.println("同步开始做任务一");
		long start = System.currentTimeMillis();
		Thread.sleep(5000);
		long end = System.currentTimeMillis();
		System.out.println("同步完成任务一，耗时：" + (end - start) + "毫秒");
		return new AsyncResult<>("同步任务一完成");
	}

	public Future<String> doTaskTwo() throws Exception {
		System.out.println("同步开始做任务二");
		long start = System.currentTimeMillis();
		Thread.sleep(5000);
		long end = System.currentTimeMillis();
		System.out.println("同步完成任务二，耗时：" + (end - start) + "毫秒");
		return new AsyncResult<>("同步任务二完成");
	}

	public Future<String> doTaskThree() throws Exception {
		System.out.println("同步开始做任务三");
		long start = System.currentTimeMillis();
		Thread.sleep(5000);
		long end = System.currentTimeMillis();
		System.out.println("同步完成任务三，耗时：" + (end - start) + "毫秒");
		return new AsyncResult<>("同步任务三完成");
	}

	public String test() throws Exception {
		long start = System.currentTimeMillis();
		Future<String> task1 = doTaskOne();
		Future<String> task2 = doTaskTwo();
		Future<String> task3 = doTaskThree();
		while (true) {
			if (task1.isDone() && task2.isDone() && task3.isDone()) {
				// 三个任务都调用完成，退出循环等待
				break;
			}
			Thread.sleep(1000);
		}
		long end = System.currentTimeMillis();
		System.out.println("同步任务全部完成，总耗时：" + (end - start) + "毫秒");
		return ("同步任务全部完成，总耗时：" + (end - start) + "毫秒");
	}
}
